﻿using System.Configuration;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Web.Mvc;
using Citi.Helpers;
using Citi.Scheduler.Domain;
using System;
using Citi.Scheduler.WindowsServices;

namespace Citi.Scheduler.WebUi.Controllers
{
    public class HomeController : ControllerBase
    {
        public ActionResult TopExecutions()
        {
            return PartialView();
        }

        public ActionResult Support()
        {
            return View();
        }

        public ActionResult TestExecutionService()
        {
            //new RoutineSchedule().SendRoutinesToExecutionQueue();
            //return RedirectToAction("Index");
            var eventlog = new EventLog
                {
                    Log = "Citi Execution Engine Service Log",
                    Source = "Citi Execution Engine Service"
                };
            var machine = "LACBRA800W0273";
            ExecutionAction.EventLog = eventlog;

            var machine1 = new Machine().GetByHostName(machine, MachineCenter.Execution);

            ExecutionAction.MachineId = machine1 != null ? machine1.Id : new Machine().GetByHostName(Environment.MachineName, MachineCenter.Execution).Id;

            ExecutionAction.StartEngine();

            return RedirectToAction("Index");
        }

        public ActionResult RunScheduler()
        {
            new RoutineSchedule().SendRoutinesToExecutionQueue(true);
            return RedirectToAction("Index");
        }

        public ActionResult TestMonitorService()
        {
            var eventlog = new EventLog
            {
                Log = "Citi Monitor Service Log",
                Source = "Citi Monitor Service"
            };
            MonitorAction.EventLog = eventlog;
            MonitorAction.StartEngine();

            return RedirectToAction("Index");
        }

        public ActionResult Index()
        {
            //var sss =RoutineParameter.FillVariables("{[Day] * 10} - {[Day] - 20}");
            //var sss2 = RoutineParameter.FillVariables("{{[Day] * 10} - {[Day] - 20}}");
            //WindowsUtil.ChangeWindowsServiceUser("Citi Scheduler Execution Service", null, null, null, @".\nathan", "waters");
            //WindowsUtil.ChangeWindowsServiceUser("Citi Scheduler Execution Service", null, null, null, "LocalSystem", null);
            //WindowsUtil.GetServiceStatus("Citi Scheduler Execution Service", "samsung-pc", 30000);
            // var laala = new Category().SelectAll<Category>();
            //CheckSharedFolders();
            //SendDashboardEmail();
            //WindowsUtil.GetProcessOwner("Citi.Scheduler.WindowsServices.exe", null,null, null);
            //NT AUTHORITY\\SYSTEM"
            //Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
            //Process[] processes = Process.GetProcessesByName("Citi.Scheduler.WindowsServices");
            //string[] OwnerInfo = new string[2];
            //processes[0].
            //long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;

            return View();
        }

        public string GetEmailBody(string templatePath)
        {
            var objWebClient = new WebClient();
            byte[] aRequestedHtml = objWebClient.DownloadData(templatePath);

            string strRequestedHtml = Encoding.UTF8.GetString(aRequestedHtml);

            return strRequestedHtml;
        }

        private void SendDashboardEmail()
        {
            var template = EmailHelper.GetEmailBody(string.Format("{0}/user.aspx/form", "http://lacbra802wl3491/scheduler"));

            var emailSchedules = new EmailSchedule().SelectAllActive<EmailSchedule>();

            foreach (var emailSchedule in emailSchedules)
            {
                if (!RoutineSchedule.RunOnDate(emailSchedule.Schedule, DateTime.Today)) return;

                if ((!emailSchedule.LastSent.HasValue || (emailSchedule.LastSent.HasValue && emailSchedule.LastSent.Value.Date < DateTime.Today)) &&
                    emailSchedule.Schedule.Time.TimeOfDay <= DateTime.Now.TimeOfDay)
                {
                    //new EmailHelper().SendEmail(new EmailHelper.EmailData
                    //{
                    //    Template = string.Format("{0}/RoutineExecution.aspx/EmailDashboard?emailScheduleId={1}", "http://localhost:25198", emailSchedule.Id),
                    //    Subject = string.Format("Dashboard: {0} at {1}", emailSchedule.Category.Name, DateTime.Now.ToString("dd/MM/yyyy hh:mm")),
                    //    To = emailSchedule.User.Soeid,
                    //});


                    //emailSchedule.LastSent = DateTime.Now;
                    //emailSchedule.Save(emailSchedule);
                }
            }
        }

        private void CheckSharedFolders()
        {
            var sharedFolders = new SharedFolder().SelectAllActive<SharedFolder>();

            foreach (var sharedFolder in sharedFolders)
            {
                //var size = WindowsUtil.GetDirectorySize(sharedFolder.SharedFolder1, NetworkUser, NetWorkPassword);
                var asas = WindowsUtil.GetSharedFreeSpace(sharedFolder.HostName, NetworkUser, NetworkPassword,
                                                          sharedFolder.SharedFolder1);
                ulong FreeBytesAvailable;
                ulong TotalNumberOfBytes;
                ulong TotalNumberOfFreeBytes;

                bool success = WindowsUtil.GetDiskFreeSpaceEx(sharedFolder.SharedFolder1, out FreeBytesAvailable, out TotalNumberOfBytes,
                                   out TotalNumberOfFreeBytes);
                if (!success)
                    throw new System.ComponentModel.Win32Exception();
            }
        }

    }
}
